package com.example.utils;

import com.example.model.WxbCustomer;
import com.example.impl.WxbCustomerServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class SellRealm extends AuthorizingRealm {

    @Autowired
    private WxbCustomerServiceImpl wxbCustomerService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

 //1、获取当前登录的用户信息
        WxbCustomer wxbCustomer = (WxbCustomer) SecurityUtils.getSubject().getPrincipal();

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//        //根据用户名查询用户对象信息
//        UserInfo userInfo = userInfoService.findUserInfoByUserName(token.getUsername());
//        if (userInfo == null) {
//            return null;
//        }
//        // 直接将其封装为 返回的数据类型
//        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), ByteSource.Util.bytes(userInfo.getAccount()), getName());
//        return authenticationInfo;

        //1.从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
//
//        String md5Pwd = new SimpleHash("MD5",password).toHex();
        String md5Pwd = new SimpleHash("md5",password,ByteSource.Util.bytes(username),56).toHex();
        //2.根据用户名查询数据库(UserDAO)
        WxbCustomer wxbCustomer = wxbCustomerService.findByLoginName(token.getUsername());

        if (wxbCustomer == null){
            throw new UnknownAccountException("账号不存在");
        }else{
            //用户存在则验证密码
            if ( !wxbCustomer.getLoginPwd().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误");
            }
        }
        return new SimpleAuthenticationInfo(wxbCustomer, wxbCustomer.getLoginPwd(), ByteSource.Util.bytes(wxbCustomer.getLoginName()), getName());
    }
}
